package com.xinghe.sharedevice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.exception.ServiceException;
import com.share.common.security.utils.SecurityUtils;
import com.xinghe.sharedevice.domain.PowerBank;
import com.xinghe.sharedevice.mapper.PowerBankMapper;
import com.xinghe.sharedevice.service.IPowerBankService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author 星河一叶Ck
 * @date 2025/5/27
 */

@Service
@RequiredArgsConstructor
public class PowerBankServiceImpl extends ServiceImpl<PowerBankMapper, PowerBank> implements IPowerBankService {

    private final PowerBankMapper powerBankMapper;

    /**
     * 查询充电宝列表
     * @param powerBank 要查询的充电宝
     * @return
     */
    @Override
    public List<PowerBank> selectPowerBankList(PowerBank powerBank) {
        return powerBankMapper.selectPowerBankList(powerBank);
    }

    @Override
    public int savePowerBank(PowerBank powerBank) {
        // 判断是否已经存在
        long count = this.count(new LambdaQueryWrapper<PowerBank>().eq(PowerBank::getPowerBankNo, powerBank.getPowerBankNo()));
        if (count > 0) {
            throw new ServiceException("充电宝编号已存在");
        }
        powerBank.setCreateTime(new Date());
        powerBank.setCreateBy(SecurityUtils.getUsername());
        powerBankMapper.insert(powerBank);
        return 1;
    }

    @Override
    public int updatePowerBank(PowerBank powerBank) {
        // 获取旧数据
        PowerBank oldPowerBank = this.getById(powerBank);
        // 确保存在且未投放
        if (oldPowerBank != null && !oldPowerBank.getStatus().equals("0")) {
            throw new ServiceException("该充电宝已投放，无法修改");
        }

        //判断柜机编号是否改变
        if (!oldPowerBank.getPowerBankNo().equals(powerBank.getPowerBankNo())) {
            // System.out.println("旧的柜机编号" + oldPowerBank);
            // System.out.println("新的柜机编号" + powerBank);
            // 判断充电宝柜机编号是否已经使用了
            long count = this.count(new LambdaQueryWrapper<PowerBank>().eq(PowerBank::getPowerBankNo, powerBank.getPowerBankNo()));
            if (count > 0) {
                throw new ServiceException("充电宝编号已被使用");
            }
        }

        powerBankMapper.updateById(powerBank);
        return 1;
    }
}
